﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace FieldTools.Util.Helper
{
    public class PythonHelper
    {
        /// <summary>
        /// 执行python脚本，传入文件路径和参数
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="parm"></param>
        /// <returns></returns>
        public static string ExcuteScriptByFile(string filePath, object parm)
        {
            if (!filePath.EndsWith(".py")) return $"\"{filePath}\"文件非python脚本";
            try
            {
                ScriptRuntime pyRumTime = Python.CreateRuntime();
                // 加载外部 python 脚本文件.
                //入口暂定为Excute
                dynamic obj = pyRumTime.UseFile(filePath);
                var res = obj.Excute(parm);

                //var engine = Python.CreateEngine();
                //var scope = engine.CreateScope();
                //var res = engine.ExecuteFile(filePath, scope);

                if (res != null) return res.ToJson();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            
            return string.Empty;
        }

        /// <summary>
        /// 执行python脚本，传入python字符串和参数
        /// </summary>
        /// <param name="scriptStr"></param>
        /// <param name="parm"></param>
        /// <returns></returns>
        public static string ExcuteScriptByStr(string scriptStr, object parm)
        {
            try
            {
                var engine = Python.CreateEngine();
                //var scope = engine.CreateScope();
                var script = engine.Execute(scriptStr);
                var res = script.Excute(parm);
                if (res != null) return res;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            
            return string.Empty;
        }
    }
}
